<template>
  <div class="home-container">
    <!-- 活动轮播图 -->
    <div class="carousel-section">
      <h2 class="section-title">精选活动</h2>
      <el-carousel :interval="4000" type="card" height="300px">
        <el-carousel-item v-for="carousel in carousels" :key="carousel.id">
          <div class="carousel-content" @click="goToActivityDetail(carousel.activityId)">
            <img :src="carousel.imageUrl" class="carousel-image" />
            <div class="carousel-info">
              <h3>{{ carousel.title }}</h3>
              <p class="carousel-desc">{{ carousel.description }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 风采展示 -->
    <div class="showcase-section">
      <h2 class="section-title">志愿风采</h2>
      <div class="showcase-list">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in showcaseList" :key="item.id">
            <el-card class="showcase-card" shadow="hover" @click="goToEvaluationDetail(item.activityId)">
              <img :src="item.imageUrl" class="showcase-image" />
              <div class="showcase-info">
                <h3>{{ item.title }}</h3>
                <p>{{ item.organization }}</p>
                <p>{{ item.date }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 统计数据展示 -->
    <div class="statistics-section">
      <h2 class="section-title">活动数据</h2>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Calendar /></el-icon>
                <span>活动总数</span>
              </div>
            </template>
            <div class="stat-content">
              <h2>{{ statistics.totalActivities }}</h2>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><User /></el-icon>
                <span>志愿者总数</span>
              </div>
            </template>
            <div class="stat-content">
              <h2>{{ statistics.totalVolunteers }}</h2>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Clock /></el-icon>
                <span>累计服务时长</span>
              </div>
            </template>
            <div class="stat-content">
              <h2>{{ statistics.totalHours }}</h2>
              <span>小时</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <el-icon><Star /></el-icon>
                <span>学分发放</span>
              </div>
            </template>
            <div class="stat-content">
              <h2>{{ statistics.totalCredits }}</h2>
              <span>分</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 管理员显示的编辑入口 -->
    <div class="admin-panel" v-if="isAdmin">
      <el-button type="primary" @click="showEditCarouselDialog">编辑轮播图</el-button>
      <el-button type="primary" @click="showEditShowcaseDialog">编辑风采展示</el-button>
      <el-button type="primary" @click="showSystemAnnouncementDialog">发布系统公告</el-button>
    </div>
    
    <!-- 编辑轮播图对话框 -->
    <el-dialog v-model="carouselDialogVisible" title="编辑轮播图" width="800px">
      <el-table :data="carousels" stripe style="width: 100%">
        <el-table-column prop="title" label="标题" width="150"></el-table-column>
        <el-table-column prop="description" label="描述" width="250"></el-table-column>
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <img :src="scope.row.imageUrl" style="height: 50px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="editCarousel(scope.row)" link>编辑</el-button>
            <el-button type="danger" @click="removeCarousel(scope.row)" link>移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-button @click="carouselDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCarousels">保存</el-button>
      </div>
    </el-dialog>
    
    <!-- 编辑风采展示对话框 -->
    <el-dialog v-model="showcaseDialogVisible" title="编辑风采展示" width="800px">
      <el-table :data="showcaseList" stripe style="width: 100%">
        <el-table-column prop="title" label="标题" width="150"></el-table-column>
        <el-table-column prop="organization" label="组织" width="150"></el-table-column>
        <el-table-column prop="date" label="日期" width="150"></el-table-column>
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <img :src="scope.row.imageUrl" style="height: 50px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="editShowcase(scope.row)" link>编辑</el-button>
            <el-button type="danger" @click="removeShowcase(scope.row)" link>移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-button @click="showcaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveShowcases">保存</el-button>
      </div>
    </el-dialog>
    
    <!-- 发布系统公告对话框 -->
    <el-dialog v-model="announcementDialogVisible" title="发布系统公告" width="600px">
      <el-form :model="announcementForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="announcementDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="publishAnnouncement">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Calendar, User, Clock, Star } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 使用可选链和空值合并操作符来安全地访问角色信息
const userInfo = computed(() => userStore.userInfo || {})
const isAdmin = computed(() => userInfo.value?.role === 3 || false)

// 轮播图数据
const carousels = ref([])
// 风采展示数据
const showcaseList = ref([])
// 统计数据
const statistics = ref({
  totalActivities: 0,
  totalVolunteers: 0,
  totalHours: 0,
  totalCredits: 0
})

// 对话框显示控制
const carouselDialogVisible = ref(false)
const showcaseDialogVisible = ref(false)
const announcementDialogVisible = ref(false)

// 公告表单
const announcementForm = ref({
  title: '',
  content: ''
})

// 获取轮播图数据
const getCarousels = async () => {
  try {
    const response = await fetch('/api/carousel/listEnabled')
    const data = await response.json()
    carousels.value = data.data || []
  } catch (error) {
    console.error('获取轮播图失败:', error)
    // 模拟数据
    carousels.value = [
      {
        id: 1,
        activityId: 101,
        title: '校园清洁日',
        description: '一起来美化我们的校园环境，共建美丽校园',
        imageUrl: 'https://picsum.photos/id/42/800/400'
      },
      {
        id: 2,
        activityId: 102,
        title: '助老敬老行动',
        description: '关爱老人，传递温暖，服务社区',
        imageUrl: 'https://picsum.photos/id/43/800/400'
      },
      {
        id: 3,
        activityId: 103,
        title: '爱心义卖活动',
        description: '为山区儿童募集爱心物资和学习用品',
        imageUrl: 'https://picsum.photos/id/44/800/400'
      }
    ]
  }
}

// 获取风采展示数据
const getShowcaseList = async () => {
  try {
    const response = await fetch('/api/showcase/list')
    const data = await response.json()
    showcaseList.value = data.data || []
  } catch (error) {
    console.error('获取风采展示失败:', error)
    // 模拟数据
    showcaseList.value = [
      {
        id: 1,
        activityId: 201,
        title: '关爱留守儿童',
        organization: '青年志愿者协会',
        date: '2023-04-15',
        imageUrl: 'https://picsum.photos/id/60/400/300'
      },
      {
        id: 2,
        activityId: 202,
        title: '垃圾分类宣传',
        organization: '环保协会',
        date: '2023-04-20',
        imageUrl: 'https://picsum.photos/id/61/400/300'
      },
      {
        id: 3,
        activityId: 203,
        title: '社区服务日',
        organization: '社会工作学院',
        date: '2023-04-25',
        imageUrl: 'https://picsum.photos/id/62/400/300'
      }
    ]
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const response = await fetch('/api/statistics/summary')
    const data = await response.json()
    statistics.value = data.data || {
      totalActivities: 0,
      totalVolunteers: 0,
      totalHours: 0,
      totalCredits: 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 模拟数据
    statistics.value = {
      totalActivities: 125,
      totalVolunteers: 2368,
      totalHours: 8720,
      totalCredits: 1450
    }
  }
}

// 跳转到活动详情
const goToActivityDetail = (activityId) => {
  router.push(`/activity/detail/${activityId}`)
}

// 跳转到活动评价
const goToEvaluationDetail = (activityId) => {
  router.push(`/evaluation/detail/${activityId}`)
}

// 显示编辑轮播图对话框
const showEditCarouselDialog = () => {
  carouselDialogVisible.value = true
}

// 显示编辑风采展示对话框
const showEditShowcaseDialog = () => {
  showcaseDialogVisible.value = true
}

// 显示系统公告对话框
const showSystemAnnouncementDialog = () => {
  announcementDialogVisible.value = true
}

// 编辑轮播图
const editCarousel = (carousel) => {
  // TODO: 实现编辑轮播图的逻辑
  console.log('编辑轮播图:', carousel)
}

// 移除轮播图
const removeCarousel = (carousel) => {
  // TODO: 实现移除轮播图的逻辑
  console.log('移除轮播图:', carousel)
}

// 保存轮播图设置
const saveCarousels = async () => {
  try {
    // TODO: 实现保存轮播图的API调用
    ElMessage.success('保存成功')
    carouselDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 编辑风采展示
const editShowcase = (showcase) => {
  // TODO: 实现编辑风采展示的逻辑
  console.log('编辑风采展示:', showcase)
}

// 移除风采展示
const removeShowcase = (showcase) => {
  // TODO: 实现移除风采展示的逻辑
  console.log('移除风采展示:', showcase)
}

// 保存风采展示设置
const saveShowcases = async () => {
  try {
    // TODO: 实现保存风采展示的API调用
    ElMessage.success('保存成功')
    showcaseDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 发布系统公告
const publishAnnouncement = async () => {
  try {
    // TODO: 实现发布系统公告的API调用
    ElMessage.success('公告发布成功')
    announcementDialogVisible.value = false
    // 清空表单
    announcementForm.value = {
      title: '',
      content: ''
    }
  } catch (error) {
    ElMessage.error('公告发布失败')
  }
}

// 在组件挂载时确保获取用户信息
onMounted(async () => {
  if (userStore.token && !userStore.userInfo?.role) {
    try {
      await userStore.getInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  getCarousels()
  getShowcaseList()
  getStatistics()
})
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  
  .section-title {
    font-size: 24px;
    margin: 30px 0;
    color: #2c3e50;
    position: relative;
    padding-left: 15px;
    font-weight: 600;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      height: 70%;
      width: 4px;
      background: linear-gradient(to bottom, #409EFF, #36D1DC);
      border-radius: 2px;
    }
  }
  
  .carousel-section {
    margin-bottom: 50px;
    
    :deep(.el-carousel__item) {
      border-radius: 12px;
      overflow: hidden;
    }
    
    .carousel-content {
      height: 100%;
      position: relative;
      cursor: pointer;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      transition: transform 0.3s ease;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .carousel-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .carousel-info {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 20px;
        background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
        color: white;
        
        h3 {
          margin: 0 0 8px;
          font-size: 20px;
          font-weight: 600;
        }
        
        .carousel-desc {
          margin: 0;
          font-size: 14px;
          line-height: 1.5;
          opacity: 0.9;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }
    }
  }
  
  .showcase-section {
    margin-bottom: 50px;
    
    .showcase-list {
      .showcase-card {
        height: 100%;
        margin-bottom: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        border-radius: 12px;
        overflow: hidden;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
        }
        
        .showcase-image {
          width: 100%;
          height: 200px;
          object-fit: cover;
          transition: transform 0.3s ease;
        }
        
        .showcase-info {
          padding: 15px;
          
          h3 {
            margin: 0 0 10px;
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
          }
          
          p {
            margin: 5px 0;
            color: #606266;
            font-size: 14px;
            display: flex;
            align-items: center;
            
            .el-icon {
              margin-right: 5px;
            }
          }
        }
      }
    }
  }
  
  .statistics-section {
    margin: 50px 0;
    
    .stat-card {
      border-radius: 12px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      }
      
      .stat-header {
        display: flex;
        align-items: center;
        padding: 15px;
        border-bottom: 1px solid #ebeef5;
        
        .el-icon {
          margin-right: 10px;
          font-size: 24px;
          color: #409EFF;
        }
        
        span {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
        }
      }
      
      .stat-content {
        text-align: center;
        padding: 20px;
        
        h2 {
          font-size: 36px;
          margin: 0;
          background: linear-gradient(45deg, #409EFF, #36D1DC);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          font-weight: bold;
        }
        
        span {
          color: #606266;
          font-size: 14px;
          margin-top: 5px;
          display: inline-block;
        }
      }
    }
  }
  
  .admin-panel {
    display: flex;
    gap: 15px;
    margin: 30px 0;
    justify-content: flex-end;
    
    .el-button {
      padding: 12px 24px;
      border-radius: 8px;
      font-weight: 500;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
      }
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .home-container {
    padding: 15px;
    
    .section-title {
      font-size: 20px;
      margin: 20px 0;
    }
    
    .carousel-section {
      margin-bottom: 30px;
      
      .carousel-content {
        .carousel-info {
          h3 {
            font-size: 18px;
          }
          
          .carousel-desc {
            font-size: 13px;
          }
        }
      }
    }
    
    .showcase-section {
      .showcase-card {
        .showcase-image {
          height: 160px;
        }
        
        .showcase-info {
          h3 {
            font-size: 16px;
          }
        }
      }
    }
    
    .statistics-section {
      .stat-card {
        margin-bottom: 15px;
        
        .stat-content {
          h2 {
            font-size: 28px;
          }
        }
      }
    }
    
    .admin-panel {
      flex-wrap: wrap;
      gap: 10px;
      
      .el-button {
        padding: 10px 20px;
      }
    }
  }
}
</style> 